package legumes.client.ui.widgets.form.item;

import legumes.client.services.callbacks.GetProductCatagoriesCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.shared.domain.ProductCategory;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.validator.CustomValidator;

public class ProductCategorytFormItem extends ComboBoxItem {
	
	private ProductCategory pc;
	private ProductCategory [] pcAr;
	
	public ProductCategorytFormItem(String initValue_){
		super("ProductCategory", "Cat&eacute;gorie");
		setWidth("70");
		setTextAlign(Alignment.LEFT);
		setValidateOnExit(true);
        setValidators(new CustomValidator(){

			@Override
			protected boolean condition(Object value) {
				ProductCategory pcFound = findProductCategory(value.toString());
				pc = pcFound;
				return pc != null;
			}
			
		});
		setValidateOnExit(true);
	    initComboMap();
	}
	
	public ProductCategory findProductCategory(String productCategory_){
		for(ProductCategory pc : pcAr){
			if(pc.getName().equalsIgnoreCase(productCategory_)){
				return pc;
			}
		}
		return null;
	}
	
	private void initComboMap() {
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		final GetProductCatagoriesCallback getProductCategoriesCallback = new GetProductCatagoriesCallback();
		callSequencer.addCall(getProductCategoriesCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				pcAr = getProductCategoriesCallback.getProductCategories();
				String [] str = new String[pcAr.length];
				int i=0;
				for( ProductCategory pc : pcAr){
					str[i] = pc.getName();
					i++;
				}
				setValueMap(str);
			}
		});
		callSequencer.callSequence();
	}

	public ProductCategory getProductCategory() {
		return pc;
	}
}
